const Router = require('koa-router')
const service = require('../service/service')
const { Book, Task } = require('../db')
const fs = require('fs')
const log4js = require('../config/log4js')
const log = log4js.getLogger()
const bookU = require('../util/book')
const userI = require('../intercepror/user')

const route = new Router({
  prefix: '/book'
})

route
  .get('/search', async ctx => {
    const { type, qsType, qs, page = 0, pageSize = 20 } = ctx.request.body
    log.info(`${ctx.user.username} searched ${qs}, page: ${page}, pageSize: ${pageSize}`)
    if (type === 'local') {
      if (qsType === 'bname') {
        const data = await Book.find({
          name: {
            $regex: qs
          }
        }).skip(parseInt(page) * parseInt(pageSize))
          .limit(parseInt(pageSize))
        ctx.body = data
      } else if (qsType === 'aname') {
        const data = await Book.find({
          author: {
            $regex: qs
          }
        }).skip(parseInt(page) * parseInt(pageSize))
          .limit(parseInt(pageSize))
        ctx.body = data
      } else {
        ctx.body = []
      }
    } else if (type === 'epubee') {
      const res = await service.getSearchList(qs)
      ctx.body = res.data
    } else {
      ctx.body = []
    }
  })

  .get('/search/local', async ctx => {
    const { qs, page = 0, pageSize = 20 } = ctx.request.body
    log.info(`${ctx.user.username} searched ${qs}, page: ${page}, pageSize: ${pageSize}`)
    const books = await Book.find({
      $or: [
        {
          name: {
            $regex: qs
          }
        },
        {
          author: {
            $regex: qs
          }
        }
      ]
    }, {
      id: 1,
      name: 1,
      author: 1,
      createTime: 1,
      creator: 1
    }).skip(parseInt(page) * parseInt(pageSize))
      .limit(parseInt(pageSize))
    ctx.body = books
  })

  .post('/epubee/task', async ctx => {
    const { bid, cover, title, author } = ctx.request.body
    const task = new Task({
      bid,
      cover,
      title,
      author,
      userid: ctx.user.id
    })

    await task.save().then(() => {
      ctx.body = 'success'
    }).catch(err => {
      ctx.throw(err)
    })
  })

  .get('/epubee/task', async ctx => {
    const myTasks = await Task.find({
      userid: ctx.user.id
    }).sort({
      createTime: ctx.request.body.sort || 1
    })
    ctx.body = myTasks
  })

  .delete('/epubee/task', async ctx => {
    const idStr = ctx.request.body.ids
    const ids = idStr.split(',')
    log.info(`${ctx.user.username} deleted tasks ${ids}`)
    await Task.deleteMany({
      _id: {
        $in: ids
      }
    })
    ctx.body = 'success'
  })

  .get('/download', userI.emailVerified, async ctx => {
    const book = await Book.findById(ctx.request.body.id)
    if (book) {
      const { name, postfix } = bookU.transferBookTitleToNameAndPostfix(book.name)
      ctx.attachment(bookU.resolveTooLongBookName2(name) + postfix)
      ctx.body = fs.readFileSync(book.uri)
    } else {
      ctx.throw('book not exists')
    }
  })

  .get('/details', userI.emailVerified, async ctx => {
    const { id } = ctx.request.body
    ctx.body = await Book.findById(id)
  })

  .post('/', userI.emailVerified, async ctx => {
    const { name, author } = ctx.request.body

    const book = new Book({
      name,
      author,
      creator: ctx.user.username,
      cover: ctx.request.files && ctx.request.files.cover ? fs.readFileSync(ctx.request.files.cover.path) : null
    })

    ctx.body = await book.save()
  })

  .post('/thirdPartyUri', userI.emailVerified, async ctx => {
    // 书籍id 第三方下载地址名称 下载地址 说明
    const { bookId, uriName, uri, comment } = ctx.request.body

    const book = await Book.findById(bookId)
    ctx.body = await book.update({
      $push: {
        thirdPartyUri: {
          uriName,
          uri,
          provider: ctx.user.username,
          comment
        }
      }
    })
  })

module.exports = route
